package com.ruiao.car.service.worm;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruiao.car.dto.WormDataDto;
import com.ruiao.car.entity.Articles;
import com.ruiao.car.entity.ArticlesChannel;
import com.ruiao.car.entity.ArticlesContent;
import com.ruiao.car.enums.AppIdEnum;
import com.ruiao.car.service.IArticlesChannelService;
import com.ruiao.car.service.IArticlesContentService;
import com.ruiao.car.service.IArticlesService;
import com.ruiao.car.utils.GsonUtils;
import com.ruiao.car.utils.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.ListUtils;
import org.thymeleaf.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jsonval on 2020/6/12.
 */
@Slf4j
public abstract class BaseWormService implements IWormService {
    @Autowired
    private IArticlesService articlesService;

    @Autowired
    private IArticlesContentService articlesContentService;

    @Autowired
    private IArticlesChannelService articlesChannelService;

    /**
     * 定时任务会自动去执行这里
     */
    public void handleWormData() throws Exception {
        List<WormDataDto> wormDataDtos = wormDate();
        for (WormDataDto wormDataDto : wormDataDtos) {

            String content = content(wormDataDto);

            if (!StringUtils.isEmpty(content)) {
                //判断是否已经爬取数据了
                int count = articlesService.count(Wrappers.<Articles>query()
                        .lambda().eq(Articles::getSourceId, wormDataDto.getSourceId()));

                if (count == 0) {
                    saveData(wormDataDto.getAppId(),
                            wormDataDto.getChannelId(),
                            wormDataDto.getSourceId(),
                            wormDataDto.getCoverImages(),
                            wormDataDto.getTitle(),
                            wormDataDto.getAbsContent(),
                            wormDataDto.getAuthor(),
                            wormDataDto.getPublishTime(),
                            wormDataDto.getOrigin(),
                            StringUtils.isEmpty(wormDataDto.getContent()) ? content : wormDataDto.getContent());
                } else {
                    log.info("数据已经入库title={},id={}", wormDataDto.getTitle(), wormDataDto.getSourceId());
                }

            } else {
                log.info("内容为null不入库" + GsonUtils.get().toJson(wormDataDto));
            }


        }
    }


    /**
     * @param appId
     * @param channelId
     * @param sourceId
     * @param coverImages
     * @param title
     * @param absContent
     * @param author
     * @param publishTime
     * @param origin
     * @param content
     */
    private void saveData(
            AppIdEnum appId,
            String channelId,
            String sourceId, List<String> coverImages,
            String title, String absContent, String author, Date publishTime,
            String origin,
            String content) {
        //保存资讯
        Articles articles = saveArticles(sourceId, coverImages, title, absContent, author, publishTime, origin);
        //内容
        saveArticlesContent(articles, content);
        //关联频道
        saveArticlesChannel(articles, appId, channelId);
    }


    /**
     * 保存资讯
     *
     * @param sourceId
     * @param coverImages
     * @param title
     * @param absContent
     * @param author
     * @param publishTime
     * @param origin
     * @return
     */
    private Articles saveArticles(String sourceId, List<String> coverImages,
                                  String title, String absContent, String author, Date publishTime,
                                  String origin) {
        String id = String.valueOf(SnowflakeIdWorker.getInstance().nextId());
        if (ListUtils.isEmpty(coverImages)) {
            coverImages = new ArrayList<>();
        }
        Articles articles = Articles.builder().id(id)
                .sourceId(sourceId)
                .coverImages(GsonUtils.get().toJson(coverImages))
                .coverCount(coverImages.size())
                .title(title)
                .abstractContent(absContent)
                .author(author)
                .publishTime(publishTime)
                .origin(origin)
                .createTime(new Date())
                .updateTime(new Date())
                .status(true)
                .build();
        articlesService.save(articles);
        return articles;
    }

    /**
     * 保存内容
     *
     * @param articles
     * @param content
     * @return
     */
    private ArticlesContent saveArticlesContent(Articles articles, String content) {
        String id = String.valueOf(SnowflakeIdWorker.getInstance().nextId());
        ArticlesContent articlesContent = ArticlesContent.builder().id(id)
                .articlesId(articles.getId())
                .content(content)
                .createTime(new Date())
                .status(true)
                .build();
        articlesContentService.save(articlesContent);
        return articlesContent;


    }

    private ArticlesChannel saveArticlesChannel(Articles articles, AppIdEnum appId, String channelId) {
        String id = String.valueOf(SnowflakeIdWorker.getInstance().nextId());

        ArticlesChannel articlesChannel = ArticlesChannel.builder().id(id)
                .appId(appId.name())
                .articlesId(articles.getId())
                .channelId(channelId)
                .createTime(new Date())
                .publishTime(articles.getPublishTime())
                .status(true)
                .build();

        articlesChannelService.save(articlesChannel);
        return articlesChannel;

    }

    /**
     * 这里写各个爬虫的具体逻辑
     *
     * @return
     */
    abstract List<WormDataDto> wormDate() throws Exception;

    /**
     * 获取详情数据
     *
     * @param wormDataDto
     * @return
     * @throws Exception
     */
    abstract String content(WormDataDto wormDataDto) throws Exception;

}
